import { createRouter, createWebHistory } from 'vue-router'

// 使用路由懒加载优化性能
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../App.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import(/* webpackChunkName: "dashboard" */ '../views/Dashboard.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')

  if (to.meta.requiresAuth && !token) {
    // 需要认证但没有token，重定向到登录页
    next('/login')
  } else if (to.name === 'Login' && token) {
    // 已登录用户访问登录页，重定向到仪表板
    next('/dashboard')
  } else {
    next()
  }
})

export default router